﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SmartSql;
using SmartSql.DyRepository;
using SX.Infrastructure;
using SX.Infrastructure.Web;
using SX.Web.Extensions;

namespace SX.Web
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        private  IHostingEnvironment HostingEnvironment { get; }
        public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
        {
            Configuration = configuration;
            HostingEnvironment = hostingEnvironment;
        }
         
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            GlobalConfiguration.WebRootPath = HostingEnvironment.WebRootPath;
            GlobalConfiguration.ContentRootPath = HostingEnvironment.ContentRootPath;
            services.LoadInstalledModules(HostingEnvironment.ContentRootPath);

            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddHttpContextAccessor(); // IHttpContextAccessor
            services.AddCustomizedDataStore(Configuration);
            services.AddCustomizedIdentity(Configuration);
            services.AddHttpClient();

            services.Configure<RazorViewEngineOptions>(
             options => { options.ViewLocationExpanders.Add(new ModuleViewLocationExpander()); });

            services.AddCustomizedMvc(GlobalConfiguration.Modules); 
            RegisterSwagger(services);
            var sp = services.BuildServiceProvider();
            var moduleInitializers = sp.GetServices<IModuleInitializer>();
            foreach (var moduleInitializer in moduleInitializers)
            {
                moduleInitializer.ConfigureServices(services);
            }

            return services.Build(Configuration, HostingEnvironment);

        }
      
        private void RegisterSwagger(IServiceCollection services)
        {
            //services.AddSwaggerGen(c =>
            //{
            //    c.SwaggerDoc("v1", new Info
            //    {
            //        Title = SERVICE_NAME,
            //        Version = "v1",
            //        Description = "https://github.com/Ahoo-Wang/SmartSql"
            //    });
            //    c.CustomSchemaIds((type) => type.FullName);
            //    var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, $"{SERVICE_NAME}.xml");
            //    if (File.Exists(filePath))
            //    {
            //        c.IncludeXmlComments(filePath);
            //    }
            //});
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseWhen(
                    context => !context.Request.Path.StartsWithSegments("/api"),
                    a => a.UseExceptionHandler("/Home/Error")
                ); 
            }
            //app.UseMultitenancy<AA>();

            app.UseWhen(
                    context => !context.Request.Path.StartsWithSegments("/api"),
                    a => a.UseStatusCodePagesWithReExecute("/Home/ErrorWithCode/{0}")
                );
            //app.UseCustomizedRequestLocalization();
            app.UseCustomizedStaticFiles(env);
            app.UseCookiePolicy();
            app.UseCustomizedIdentity();
            app.UseCustomizedMvc();
            var moduleInitializers = app.ApplicationServices.GetServices<IModuleInitializer>();
            foreach (var moduleInitializer in moduleInitializers)
            {
                moduleInitializer.Configure(app, env);
            }
        }
    }
}
